class Profile < ActiveRecord::Base
  belongs_to :contact
  belongs_to :reference, :polymorphic => true

  validates_presence_of :reference_id, :contact_id

  VALID_PROFILE_TYPES = [ "Descriptor", "Country", "Thematic"]

  def self.search(contact_id, contact_name, page)
    items_per_page = count_record_per_page :profiles
    order = "contacts.last_name"
    conditions_clauses = []
    conditions_options = []

    if !contact_id.nil?
      conditions_clauses << "contact_id = ?"
      conditions_options << contact_id
    end

    if contact_name != ""
      conditions_clauses << "upper(contacts.last_name) like upper(?)"
      conditions_options << "%#{contact_name}%"
    end

    conditions = [conditions_clauses.join(" AND "), conditions_options].flatten
    @profiles = paginate :per_page => items_per_page,:page => page, :include => :contact, :conditions => conditions, :order => order
    return @profiles
  end

  def self.contacts_has_profile_by_countries(countries)
    countries_id = []
    countries.each { |country| countries_id << country.id  }
    profiles = Profile.find(:all, :conditions => ["reference_type = 'Country' and reference_id in (?)", countries_id])
    contacts = []
    profiles.each { |profile| if !contacts.include?(profile.contact) then contacts << profile.contact end }
    return contacts
  end
end

